package com.saris.primego.task;

import com.saris.primego.dao.OrderRepository;
import com.saris.primego.pojo.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    private final OrderRepository orderRepository;

    public OrderTask(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    /**
     * 处理超时订单的方法
     */
//    @Scheduled(cron = "0 * * * * ? ") //每分钟触发一次
    public void processTimeoutOrder() {
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // select * from orders where status = ? and order_time < (当前时间 - 15分钟)
        List<Orders> pendingOrders = orderRepository.getAllByStatus(Orders.PENDING_PAYMENT).stream().filter(o -> o.getOrderTime().isBefore(time)).toList();

        if (!pendingOrders.isEmpty()) {
            for (Orders orders : pendingOrders) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderRepository.saveAndFlush(orders);
            }
        }
    }

    /**
     * 处理一直处于派送中状态的订单
     */
//    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点触发一次
    public void processDeliveryOrder() {
        log.info("定时处理处于派送中的订单：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> pendingOrders = orderRepository.getAllByStatus(Orders.DELIVERY_IN_PROGRESS).stream().filter(o -> o.getOrderTime().isBefore(time)).toList();

        if (!pendingOrders.isEmpty()) {
            for (Orders orders : pendingOrders) {
                orders.setStatus(Orders.COMPLETED);
                orderRepository.saveAndFlush(orders);
            }
        }
    }
}
